package com.ygqh.baby.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.mongodb.gridfs.GridFSFile;
import com.ygqh.baby.mapper.YgUserMapper;
import com.ygqh.baby.model.YgUserModel;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserExample;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.utils.FileUtil;
import com.ygqh.baby.utils.GridFSUtil;

@Service
public class YgUserServiceImpl implements YgUserService {

	@Autowired
	private YgUserMapper ygUserMapper;

	@Value("${tempfile.path}")
	private String imageUploadTempUrl;

	@Override
	public YgUser findUserById(Long id) {
		return ygUserMapper.selectByPrimaryKey(id);
	}

	@Override
	public YgUser findByUserName(String username) {
		YgUserExample example = new YgUserExample();
		example.createCriteria().andUserNameEqualTo(username).andStatusEqualTo("Valid");
		List<YgUser> users = null;
		try {
			users = ygUserMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		if (null != users && !users.isEmpty()) {
			return users.get(0);
		}
		return null;
	}

	@Override
	public String saveHeadImageToMongo(String headImageUrl, String userName) {
		String fileId = null;
		try {
			File file = FileUtil.downloadFileByUrl(headImageUrl, imageUploadTempUrl, userName + ".jpg");
			GridFSFile saveFile = GridFSUtil.saveFile(file, Boolean.TRUE);
			if (saveFile != null) {
				fileId = saveFile.getId().toString();
			}
			if (file != null && file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileId;
	}

	@Override
	public YgUserModel findModelById(Long id) {
		return ygUserMapper.selectUserInfo(id);
	}

	@Override
	public YgUser findByOpenId(String openId) {
		YgUserExample example = new YgUserExample();
		example.createCriteria().andOpenIdEqualTo(openId).andStatusEqualTo("Valid");
		List<YgUser> users = null;
		try {
			users = ygUserMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		if (null != users && !users.isEmpty()) {
			return users.get(0);
		}
		return null;
	}

	@Override
	public List<YgUserModel> findModelByIds(List<Long> ids) {
		if (CollectionUtils.isEmpty(ids)) {
			return new ArrayList<>();
		}
		return ygUserMapper.selectUserInfoByIds(ids);
	}
	
}
